from rest_framework import serializers
from .models import Stock, StockPrice

class StockSerializer(serializers.ModelSerializer):
    """股票基本信息序列化器"""
    class Meta:
        model = Stock
        fields = '__all__'

class StockPriceSerializer(serializers.ModelSerializer):
    """股票价格历史数据序列化器"""
    stock_code = serializers.CharField(source='stock.code', read_only=True)
    stock_name = serializers.CharField(source='stock.name', read_only=True)
    
    class Meta:
        model = StockPrice
        fields = ['id', 'stock', 'stock_code', 'stock_name', 'date', 'open_price', 
                  'close_price', 'high_price', 'low_price', 'volume', 'amount']

class StockDetailSerializer(serializers.ModelSerializer):
    """带有最新价格的股票详情序列化器"""
    latest_price = serializers.SerializerMethodField()
    
    class Meta:
        model = Stock
        fields = ['id', 'code', 'name', 'industry', 'market', 'is_active', 'latest_price']
    
    def get_latest_price(self, obj):
        latest = obj.prices.order_by('-date').first()
        if latest:
            return {
                'date': latest.date,
                'close': latest.close_price,
                'change': latest.close_price - latest.open_price,
                'change_percent': (latest.close_price - latest.open_price) / latest.open_price * 100 if latest.open_price else 0
            }
        return None